package 线程池;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/4/24 11:12
 * @description:
 * @version:
 */
public class MyTest {
    public static void main(String[] args) {
        //1.创建一个线程池对象
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5,10,1, TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(10), Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
        //2.循环创建任务对象
        /*for (int i = 0; i < 20; i++) {
            MyTask myTask = new MyTask("客户" + i);
            pool.submit(myTask);
        }*/
        AtomicInteger num = new AtomicInteger(0);
        int size = 100;
        CountDownLatch latch = new CountDownLatch(size);
        long start = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            Runnable runnable = () -> {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
                num.getAndIncrement();
            };
            pool.submit(runnable);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("总耗时" + time);
        System.out.println(num.getAndIncrement());
        //3.关闭线程池
        pool.shutdown();
    }
}